﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media;

namespace Microsoft.Samples.Office.UnifiedCommunications.Gadget
{
    public class ColorUtility
    {
        public static Color GetColorBrush(string colorBrush)
        {
            Color actColor;
            int r,g,b;
            r=0;
            g=0;
            b=0;

            if ((colorBrush.StartsWith("#")) && (colorBrush.Length == 7))
            {
                r = HexToInt(colorBrush.Substring(1, 2));
                g = HexToInt(colorBrush.Substring(3, 2));
                b = HexToInt(colorBrush.Substring(5, 2));
                actColor = Color.FromRgb((byte)r, (byte)g, (byte)b);
            }
            else
            {
                actColor = Color.FromRgb(255, 255, 255);
            }
            return actColor;
        }


      private static int HexToInt(String hexstr)
        {
            int counter, hexint;
            char[] hexarr;
            hexint = 0;
            hexstr = hexstr.ToUpper();
            hexarr = hexstr.ToCharArray();
            for (counter = hexarr.Length - 1; counter >= 0; counter--)
            {
                if ((hexarr[counter] >= '0') && (hexarr[counter] <= '9'))
                {
                    hexint += (hexarr[counter] - 48) * ((int)(Math.Pow(16, hexarr.Length - 1 - counter)));
                }
                else
                {
                    if ((hexarr[counter] >= 'A') && (hexarr[counter] <= 'F'))
                    {
                        hexint += (hexarr[counter] - 55) * ((int)(Math.Pow(16, hexarr.Length - 1 - counter)));
                    }
                    else
                    {
                        hexint = 0;
                        break;
                    }
                }
            }
            return hexint;
        }
    }
}
